<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" label-width="110px">
      <el-row :gutter="20">
        <el-col :span="4.8">
          <el-form-item label="姓名" prop="empName">
            <el-input v-model="queryParams.empName" placeholder="请输入姓名" clearable @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="4.8">
          <el-form-item label="工号" prop="empNo">
            <el-input v-model="queryParams.empNo" placeholder="请输入工号" clearable @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="4.8">
          <el-form-item label="人员类型" prop="empType">
            <el-select v-model="queryParams.empType" placeholder="请选择人员类型" clearable>
              <el-option v-for="dict in employees_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4.8">
          <el-form-item label="所属业务" prop="businessType">
            <el-select v-model="queryParams.businessType" placeholder="请选择所属业务" clearable>
              <el-option v-for="dict in business_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4.8">
          <el-form-item label="有无头像" prop="hasAvatar">
            <el-select v-model="queryParams.hasAvatar" placeholder="请选择有无头像" clearable>
              <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4.8">
          <el-form-item label="是否设置过授权" prop="isAuthorized">
            <el-select v-model="queryParams.isAuthorized" placeholder="请选择是否设置过授权" clearable>
              <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="String(dict.value)" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4.8">
          <el-form-item label="授权状态" prop="auth_status">
            <el-select v-model="queryParams.auth_status" placeholder="请选择授权状态" clearable>
              <el-option v-for="dict in auth_status" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4.8">
          <el-form-item label="所属部门" prop="departmentId">
            <el-select v-model="queryParams.departmentId" placeholder="请选择所属部门" clearable>
              <el-option v-for="dept in deptList" :key="dept.deptId" :label="dept.deptName" :value="dept.deptId" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4.8">
          <el-form-item label="是否为车长" prop="isRouteLeader">
            <el-select v-model="queryParams.isRouteLeader" placeholder="请选择是否为车长" clearable>
              <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4.8">
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['service:employees:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['service:employees:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['service:employees:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Edit" :disabled="single" @click="handleUpdatePdaPwd"
          v-hasPermi="['service:employees:edit']">修改PAD登录密码</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Refresh" :disabled="single" @click="handleResetPdaPwd"
          v-hasPermi="['service:employees:edit']">重置PAD登录密码</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="upload" @click="handleImport"
          v-hasPermi="['service:employees:add']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExportTemplate"
          v-hasPermi="['service:employees:exportTemplate']">导入模版</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['service:employees:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="employeesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="姓名" align="center" prop="empName" width="200px" />
      <el-table-column label="性别" align="center" prop="sex" width="100px">
        <template #default="scope">
          <dict-tag :options="sys_user_sex" :value="scope.row.sex" />
        </template>
      </el-table-column>
      <el-table-column label="人员类型" align="center" prop="empType" width="150px">
        <template #default="scope">
          <dict-tag :options="employees_type" :value="scope.row.empType" />
        </template>
      </el-table-column>
      <el-table-column label="身份证号" align="center" prop="idno" width="150px">
        <template #default="scope">
          <span>{{ scope.row.idno ? scope.row.idno.slice(-4) : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center" prop="mobile" width="150px" />
      <el-table-column label="工号" align="center" prop="empNo" width="130px" />
      <el-table-column label="区域" align="left" prop="areaId" width="160px" show-overflow-tooltip="true">
        <template #default="scope">
          <span>{{ areaList.find(item => item.id == scope.row.areaId)?.districtComb || '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属机构" align="center" prop="organizationId" width="200px" >
        <template #default="scope">
          <span>{{ getParentOrgName(scope.row.organizationId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属部门" align="center" prop="departmentId" width="130px">
        <template #default="scope">
          <span>{{ deptList.find(item => item.deptId == scope.row.departmentId)?.deptName || ''}}</span>
        </template>
      </el-table-column>
      <el-table-column label="微信账号" align="center" prop="wxId" width="130px" />
      <el-table-column label="持枪证" align="center" prop="firearmCertNo" width="150px" />
      <el-table-column label="保安员证" align="center" prop="securityCertNo" width="150px" />
      <el-table-column label="清机员状态" align="center" prop="pdaAdmin" width="150px">
        <template #default="scope">
          <dict-tag :options="sys_yes_no" :value="scope.row.pdaAdmin" />
        </template>
      </el-table-column>
      <el-table-column label="授权状态" align="center" prop="authorizeStatus" width="150px">
        <template #default="scope">
          <dict-tag :options="auth_status" :value="scope.row.authorizeStatus" />
        </template>
      </el-table-column>
      <el-table-column label="授权银行" align="center" prop="authorizeBank" />
      <el-table-column label="身份验证指纹" align="center" prop="identityFingerprint" width="180" />
      <el-table-column label="备用身份验证指纹" align="center" prop="backupFingerprint" width="180" />
      <el-table-column label="胁迫验证指纹" align="center" prop="duressFingerprint" width="180" />
      <el-table-column label="是否为车长" align="center" prop="isRouteLeader" width="150">
        <template #default="scope">
          <dict-tag :options="sys_yes_no" :value="scope.row.isRouteLeader" />
        </template>
      </el-table-column>
      <el-table-column label="所属业务" align="center" prop="businessType" width="150px">
        <template #default="scope">
          <dict-tag :options="business_type" :value="scope.row.businessType" />
        </template>
      </el-table-column>
      <el-table-column label="最后一次登录时间" align="center" prop="lastLoginTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.lastLoginTime, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改人员管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body draggable>
      <el-form ref="employeesRef" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="姓名" prop="empName">
          <el-input v-model="form.empName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择性别">
            <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="人员类型" prop="empType">
          <el-select v-model="form.empType" placeholder="请选择人员类型">
            <el-option v-for="dict in employees_type" :key="dict.value" :label="dict.label" :value="dict.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="身份证号" prop="idno">
          <el-input v-model="form.idno" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="是否为车长" prop="isRouteLeader">
          <el-select v-model="form.isRouteLeader" placeholder="请选择是否为车长" clearable>
            <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属业务" prop="businessType">
          <el-select v-model="form.businessType" placeholder="请选择所属业务" clearable>
            <el-option v-for="dict in business_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否兼职" prop="isPartTime">
          <el-select v-model="form.isPartTime" placeholder="请选择是否兼职" clearable>
            <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工号" prop="empNo">
          <el-input v-model="form.empNo" placeholder="请输入工号" />
        </el-form-item>
        <el-form-item label="微信账号" prop="wxId">
          <el-input v-model="form.wxId" placeholder="请输入微信账号" />
        </el-form-item>
        <el-form-item label="保安证号" prop="securityCertNo">
          <el-input v-model="form.securityCertNo" placeholder="请输入保安员证" />
        </el-form-item>
        <el-form-item label="持枪证号" prop="firearmCertNo">
          <el-input v-model="form.firearmCertNo" placeholder="请输入持枪证" />
        </el-form-item>
        <el-form-item label="清分员PAD权限" prop="pdaPermis">
          <el-select v-model="form.pdaPermis" placeholder="请选择清分员PAD权限" clearable>
            <el-option v-for="dict in pda_permis" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属机构" prop="organizationId">
          <el-cascader v-model="form.organizationId" :options="organizationOptions" :props="cascaderProps" placeholder="请选择上级机构"
            clearable filterable style="width: 100%">
          </el-cascader>
        </el-form-item>
        <el-form-item label="所属区域" prop="areaId">
          <el-select v-model="form.areaId" placeholder="请选择所属机构" clearable>
            <el-option v-for="area in areaList" :key="area.id" :label="area.districtComb" :value="area.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属部门" prop="departmentId">
          <el-select v-model="form.departmentId" placeholder="请选择所属部门" clearable>
            <el-option v-for="dept in deptList" :key="dept.deptId" :label="dept.deptName" :value="dept.deptId" />
          </el-select>
        </el-form-item>
        <el-form-item label="授权情况" prop="authorizeStatus">
          <el-select v-model="form.authorizeStatus" placeholder="请选择清分员PAD权限" clearable>
            <el-option v-for="dict in auth_status" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="身份验证指纹" prop="area">
          <el-row :gutter="10">
            <el-col :span="16">
              <el-input v-model="form.identityFingerprint" placeholder="请录入身份验证指纹" clearable />
            </el-col>
            <el-col :span="8">
              <el-button size="small" type="primary" @click="handleEnrollFingerprint">开始录入指纹</el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="备份身份验证指纹" prop="area">
          <el-row :gutter="10">
            <el-col :span="16">
              <el-input v-model="form.backupFingerprint" placeholder="请录入身份验证指纹" clearable />
            </el-col>
            <el-col :span="8">
              <el-button size="small" type="primary" @click="handleEnrollFingerprint">开始录入指纹</el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="胁迫验证指纹" prop="area">
          <el-row :gutter="10">
            <el-col :span="16">
              <el-input v-model="form.duressFingerprint" placeholder="请录入胁迫验证指纹" clearable />
            </el-col>
            <el-col :span="8">
              <el-button size="small" type="primary" @click="handleEnrollFingerprint">开始录入指纹</el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="授权银行" prop="authorizeBank">
          <el-input v-model="form.authorizeBank" placeholder="请输入授权银行名称" clearable />
        </el-form-item>
        <el-form-item label="相片" prop="photoUrl">
          <el-input v-model="form.photoUrl" placeholder="请输入头像照片" />
          <image-upload v-model="form.photoUrl"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
              @click="handleExportTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 修改PDA登录密码对话框 -->
    <el-dialog title="修改PDA登录密码" v-model="pdaPwdOpen" width="500px" append-to-body>
      <el-form ref="pdaPwdRef" :model="form" :rules="rules_pda" label-width="120px">
        <el-form-item label="姓名" prop="empName">
          <el-input v-model="form.empName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="清机员类型" prop="empType">
          <el-select v-model="form.empType" disabled>
            <el-option v-for="dict in employees_type" :key="dict.value" :label="dict.label" :value="dict.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="PDA登录名称" prop="empNo">
          <el-input v-model="form.empNo" disabled />
        </el-form-item>
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="form.oldPassword" placeholder="请输入原密码" type="password" show-password />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="form.newPassword" placeholder="请输入新密码" type="password" show-password />
        </el-form-item>
        <el-form-item label="新密码确认" prop="confirmPassword">
          <el-input v-model="form.confirmPassword" placeholder="请确认新密码" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="updatePdaPwd">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 重置密码对话框 -->
    <el-dialog title="重置密码" v-model="resetPwdOpen" width="500px" append-to-body>
      <div class="dialog-content">
        是否确定重置该人员的PDA登录密码？
      </div>
      <template #footer>
        <el-button type="primary" @click="resetPdaPwd">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </template>
    </el-dialog>

    <!-- 机构管理对话框 选择对话框 -->
    <el-dialog title="选择机构" v-model="orgOpen" width="40%" append-to-body>
      <Organization :is-modal="false" :center="false" />
      <template #footer>
        <el-button type="primary" @click="handleSelectOrgConfirm">确 定</el-button>
        <el-button @click="handleSelectOrgCancel">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Employees">
import { getToken } from "@/utils/auth";
import { listEmployees, getEmployees, delEmployees, addEmployees, updateEmployees, updateEmployeesPdaPwd, resetEmployeesPdaPwdPwd, importEmployees, exportEmployeesTemplate } from "@/api/service/employees"
import { areaList, getAreaList, deptList, getDeptList, cascaderProps, organizationOptions, allOrganizations, getOrganizationList, getParentOrgName} from "@/api/common";
import { valueEquals } from "element-plus";
import { id } from "element-plus/es/locales.mjs";


const { proxy } = getCurrentInstance()
const { sys_yes_no, sys_user_sex, employees_type, business_type, pda_permis, auth_status } = proxy.useDict('sys_yes_no', 'sys_user_sex', 'employees_type', 'business_type', 'pda_permis', 'auth_status')

const employeesList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const orgOpen = ref(false) // 机构管理对话框显示控制
const selectedOrg = ref(null) // 选定的机构

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    empName: null,
    empType: null,
    empNo: null,
    employmentStatus: null,
    areaId: null,
    organizationId: null,
    departmentId: null,
    authorizeStatus: null,
    isAuthorized: null,
    pdaPwd: null,
    pdaPermis: null,
    clearmanStatus: null,
    isRouteLeader: null,
    isPartTime: null,
    businessType: null
  },
  // 用户导入参数
  upload: {
    // 是否显示弹出层（用户导入）
    open: false,
    // 弹出层标题（用户导入）
    title: "",
    // 是否禁用上传
    isUploading: false,
    // 是否更新已经存在的用户数据
    updateSupport: 0,
    // 设置上传的请求头部
    headers: { Authorization: "Bearer " + getToken() },
    // 上传的地址
    url: import.meta.env.VITE_APP_BASE_API + "/service/employees/import"
  },

  rules: {
    empName: [
      { required: true, message: "姓名不能为空", trigger: "blur" }
    ],
    sex: [
      { required: true, message: "性别不能为空", trigger: "change" }
    ],
    empType: [
      { required: true, message: "人员类型不能为空", trigger: "change" }
    ],
    empNo: [
      { required: true, message: "员工不能为空", trigger: "blur" }
    ],
    isRouteLeader: [
      { required: true, message: "是否为车长不能为空", trigger: "change" }
    ],
    businessType: [
      { required: true, message: "业务类型不能为空", trigger: "change" }
    ],
    oldPassword: [
      { required: true, message: "原密码不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules, upload } = toRefs(data)

/** 查询人员管理列表 */
function getList() {
  loading.value = true
  listEmployees(queryParams.value).then(response => {
    employeesList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  pdaPwdOpen.value = false
  resetPwdOpen.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    empName: null,
    sex: null,
    empType: null,
    idno: null,
    mobile: null,
    empNo: null,
    employmentStatus: null,
    areaId: null,
    serviceCertificate: null,
    organizationId: null,
    departmentId: null,
    wxId: null,
    firearmCertNo: null,
    securityCertNo: null,
    authorizeStatus: null,
    authorizeBank: null,
    photoUrl: null,
    clearPdaEnable: null,
    password: null,
    pdaAdmin: null,
    isRouteLeader: null,
    businessType: null,
    identityFingerprint: null,
    backupFingerprint: null,
    duressFingerprint: null,
    clearmanStatus: null,
    isAuthorized: null,
    isPartTime: null,
    lastLoginTime: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    deleted: null,
    // 👇 新增：PDA密码字段（始终初始化为 null）
    oldPassword: null,
    newPassword: null,
    confirmPassword: null
  }
  proxy.resetForm("employeesRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 选择所属机构 */
function handleOrgSelector() {
  orgOpen.value = true
}

/** 确定选择机构 */
function handleSelectOrgConfirm() {
  if (selectedOrg.value) {
    form.value.organizationId = selectedOrg.value.id
  }
  orgOpen.value = false
}

/** 取消选择机构 */
function handleSelectOrgCancel() {
  orgOpen.value = false
}

/** 处理机构选择 */
function handleOrgSelect(org) {
  selectedOrg.value = org
}

/** 清除所属机构 */
function clearOrganization() {
  form.value.organizationId = ''
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "新增人员信息"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getEmployees(_id).then(response => {
    // 确保 empType 类型与字典值类型一致
    response.data.empType = String(response.data.empType)
    // 确保 businessType 类型与字典值类型一致
    response.data.businessType = String(response.data.businessType)
    // 确保清分员PAD权限类型与字典值类型一致
    response.data.pdaPermis = response.data.pdaPermis != 0 ? String(response.data.pdaPermis) : ""
    form.value = response.data
    open.value = true
    title.value = "修改人员信息"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["employeesRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateEmployees(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addEmployees(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const tableIds = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除表编号为"' + tableIds + '"的数据项？').then(function () {
    return delEmployees(tableIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });

}

const pdaPwdOpen = ref(false)
const rules_pda = ref({
  oldPassword: [
    { required: true, message: "旧密码不能为空", trigger: "blur" }
  ],
  newPassword: [
    { required: true, message: "新密码不能为空", trigger: "blur" },
    { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" }
  ],
  confirmPassword: [
    { required: true, message: "请确认新密码", trigger: "blur" },
    {
      validator: (rules, value, callback) => {
        if (value !== form.value.newPassword) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
});

const resetPwdOpen = ref(false)
/** 重置PAD登录密码 按钮操作 */
function handleResetPdaPwd(row) {
  resetPwdOpen.value = true
}

/** 确定-重置PAD登录密码 */
function resetPdaPwd(row) {
  const _id = row.id || ids.value
  resetEmployeesPdaPwdPwd(_id).then(response => {
    proxy.$modal.msgSuccess("修改成功")
    resetPwdOpen.value = false
    getList()
  })
}

/** 修改PAD登录密码 按钮操作 */
function handleUpdatePdaPwd(row) {

  form.value.oldPassword = null      // 清空原密码表单
  form.value.newPassword = null      // 清空新密码表单
  form.value.confirmPassword = null  // 清空新密码确认表单
  proxy.resetForm("pdaPwdRef")    // 清空PDA密码表单内容

  const _id = row.id || ids.value
  getEmployees(_id).then(response => {
    // 确保 empType 类型与字典值类型一致
    response.data.empType = String(response.data.empType)
    form.value = response.data
    pdaPwdOpen.value = true
  })
}

/** 确定-修改PAD登录密码 */
function updatePdaPwd() {
  proxy.$refs["pdaPwdRef"].validate(valid => {
    if (valid) {
      updateEmployeesPdaPwd(form.value.id, form.value.oldPassword, form.value.confirmPassword).then(response => {
        proxy.$modal.msgSuccess("修改成功")
        pdaPwdOpen.value = false
        getList()
      })
    }
  })
}

/** 导入按钮操作 */
function handleImport() {
  upload.value.title = "用户导入";
  upload.value.open = true;
}

/** 下载模板操作 */
function importTemplate() {
  handleExportTemplate();
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.value.isUploading = true;
}

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.value.open = false;
  upload.value.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getList();
}

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}

/** 导入模板下载按钮操作 */
function handleExportTemplate() {
  exportEmployeesTemplate().then(response => {
    const fileName = '人员导入模板.xls';
    proxy.$download.saveAs(response, fileName);
  }).catch(error => {
    proxy.$modal.notifyError("模板下载失败");
    console.error('Download error:', error);
  });
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download('service/employees/export', {
    ...queryParams.value
  }, `employees_${new Date().getTime()}.xlsx`)
}



getAreaList();
getDeptList();
getOrganizationList()
getList()

</script>
<!-- 全局设置el-input宽度 -->
<style scoped>
:deep(.el-input),
:deep(.el-select .el-input) {
  width: 215px;
  box-sizing: border-box;
}
</style>